package com.xyoto.community.utils;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;
import org.apache.http.client.HttpClient;

import java.io.IOException;
import java.util.List;

/**
 * 企业微信机器人
 */
@Service
@Slf4j
public class ChatBotSentUtil implements ChatBotSent{

    private static final String webHook = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=866f8a5f-e059-4e81-b851-0533081fb7aa";

    static HttpClient httpClient = HttpClients.createDefault();

    @Override
    public void textSend(String content, List<String> mobileList) {

        JSONObject messageJson = new JSONObject();
        JSONObject text = new JSONObject();
        JSONArray mobileJsonArray = new JSONArray();

        text.put("content",content);
        messageJson.put("msgtype","text");

        if (0 != mobileList.size()){
            mobileJsonArray.addAll(mobileList);
        }

        text.put("mentioned_mobile_list", mobileJsonArray);
        messageJson.put("text", text);

        HttpPost httpPost = new HttpPost(webHook);
        httpPost.addHeader("Content-Type", "application/json; charset=utf-8");
        StringEntity se = new StringEntity(messageJson.toJSONString(),"utf-8");
        httpPost.setEntity(se);

        try {

            HttpResponse response = httpClient.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                String result = EntityUtils.toString(response.getEntity());
                JSONObject obj = JSONObject.parseObject(result);
                log.info("企业微信机器人日志输出" + obj);
            }
        }catch (Exception e){
            log.info("企业微信机器人报错" + e);
        }

    }

}
